/**
 * 网络请求
 */
export class NetworkUtil {
    private static request(method: "GET" | "POST", url: string, data?: any): Promise<any> {
        let p = new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.timeout = 5000;
            xhr.ontimeout = () => {
                reject("timeout");
            };
            xhr.onabort = () => {
                reject("user abort");
            };
            xhr.onerror = () => {
                reject("network error");
            };
            xhr.onreadystatechange = () => {
                if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
                    var response = xhr.responseText;
                    resolve(response);
                }
            };
            if (method == "GET") {
                xhr.open("GET", url, true);
                xhr.send();
            } else if (method == "POST") {
                xhr.open("POST", url, true);
                xhr.send(data);
            }
        });
        return p;
    }

    /**
     * GET请求
     * @param url 链接
     * @param data 参数，一般为JSON对象
     */
    public static get(url: string, data?: any): Promise<any> {
        return this.request("GET", url, data);
    }

    /**
     * POST请求
     * @param url 链接
     * @param data 参数，一般为JSON对象
     */
    public static post(url: string, data?: any): Promise<any> {
        return this.request("POST", url, data);
    }

    /**
     * 把JSON转为类对象
     * @param cla Class对象类型
     * @param json JSON字符串或JSON
     * @returns 对象
     * @example 调用示例：HttpRequest.inst.toInstanceClass(Foo, json)
     */
    public static toInstanceClass<T>(cla: new (...args: any[]) => T, json: string | object): T {
        if (typeof json === "string") {
            return Object.assign(new cla(), JSON.parse(json));
        } else {
            return Object.assign(new cla(), json);
        }
    }
}
